import $ from "jquery"

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  // console.log('接收')
  if(request.cmd === 'open') {
    $('.hide-center').fadeIn()
  } else if (request.cmd === 'xhr') {
    // console.log('接收-xhr')
    let commission_rate_base = request.value
    let td = $('.table>tbody>tr').eq(request.index).find('td').eq(3)
    let commission_rate = parseFloat(td.find('.integer')[0].innerText
      + td.find('.pointer')[0].innerText
      + td.find('.decimal')[0].innerText)
    if (commission_rate_base) {
      let td_span = $(td.children()[0])
      if (commission_rate > commission_rate_base) {
        td_span.append(`<p class="my-tip success">通过。当前：${commission_rate_base.toFixed(2)}%</p>`)
      } else if (commission_rate === commission_rate_base) {
        td_span.append(`<p class="my-tip">持平。当前：${commission_rate_base.toFixed(2)}%</p>`)
      } else if (commission_rate < commission_rate_base) {
        td_span.append(`<p class="my-tip fail">失败。当前：${commission_rate_base.toFixed(2)}%</p>`)
      }
    }
  } else if (request.cmd === 'init') {
    init()
  }
});
setTimeout(() => {
  $('.applying-nav').eq(1).click(()=>{
    init()
  })
}, 4000)
function getInfo (item_url, index) {
  return new Promise(resolve => {
    // console.log('发送')
    chrome.runtime.sendMessage({cmd: "xhr", item_url: item_url, index: index})
    resolve()
  })
}
function startSearch() {
  let timer = setInterval(async () => {
    if (document.querySelector('.table[id^="mx_n_"]')) {
      clearInterval(timer)
      loading.open()
      let trs = $('.table>tbody>tr')
      let len = trs.length
      if (!len) return
      for (let i = 0; i < len; i++) {
        let item_url = $(trs[i]).find('a.overflow_dotted')[0].href
        let item_id = item_url.match(/(?<=id=)\d+/)[0]
        await getInfo(item_id, i)
      }
      setTimeout(() => {
        $('.pagination>a').on('click', ()=>{
          init()
        })
      }, 3000)
      $('.filters-bar .dropdown-menu>li').click(()=>{
        init()
      })
      $(".w200").keyup(function(e){
        if (e.keyCode === 13) {
          init()
        }
      })
      loading.close()
    }
  }, 500)
}

const loading = {
  open: () => {
    let markNode = document.querySelector('.lds-spinner')
    if (markNode) return
    let template = document.createElement('div')
    template.className = 'lds-spinner'
    template.innerHTML = `<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>`
    document.body.appendChild(template)
  },
  close: () => {
    let markNode = document.querySelector('.lds-spinner')
    if (markNode) markNode.remove()
  }
}
let loginHtml = `<div class="hide-center">
    <div id="formhead">
        <div id="formhead-title">
            User Login
        </div>
        <button type="button" id="popup-close">X</button>
    </div>
    <div id="formbody">
        <div class="loginUserName">
            <input id="input-topright-loginInput" name="userName" class="loginInput" placeholder="userName" type="text" value="admin">
        </div>
        <div class="loginPassword">
            <input id="input-bottomright-loginInput" name="password" class="loginInput" placeholder="password" type="password" style="border-bottom-right-radius:5px;">
        </div>
        <div id="formfoot">
            <button id="BSignIn" type="submit">Sign In</button>
        </div>
    </div>
    <div id="my-tip"></div>
</div>`
$(document.body).append(loginHtml)
$('#popup-close').click(() => {
  $('.hide-center').fadeOut()
})
function toast (str) {
  $("#my-tip").text(str).fadeIn(500).fadeOut(3000)
}
$('#BSignIn').click(() => {
  let n = $('#input-topright-loginInput').val()
  let p = $('#input-bottomright-loginInput').val()
  $.get('https://www.968.cool/api/chrome_login/', {
    loginName: n,
    password: p
  }, r => {
    if (typeof r === 'string') r = JSON.parse(r)
    if (r.code === 200) {
      chrome.storage.sync.set({loginTime: new Date().getTime(), username: n})
      $('.hide-center').fadeOut()
      init()
    }
    toast(r.msg)
  })
})

function init() {
  chrome.storage.sync.get({loginTime: new Date().getTime(), username: ''}, function (items) {
    if (items.username) {
      let now = new Date().getTime()
      let hours = (now - items.loginTime) / 1000 / 60 / 60
      if (hours > 12) {
        chrome.storage.sync.set({username: ''})
        $('.hide-center').fadeIn()
      } else {
        startSearch()
      }
    } else {
      $('.hide-center').fadeIn()
    }
  })
}
